#include "tacheStockage.h"
#include "config.h"
#include <stdio.h>
 
//TODO : V�rifier la r�ception des structures de stockage
int Stockage(MSG_Q_ID _idBalPalettes, MSG_Q_ID _idBalLogs, MSG_Q_ID _idBalIHM,MSG_Q_ID _idBalErreurs)
{
	moteur_Stockage(_idBalPalettes, _idBalLogs, _idBalIHM,_idBalErreurs);
}

void moteur_Stockage(MSG_Q_ID idBalPalettes, MSG_Q_ID idBalLogs, MSG_Q_ID idBalIHM, MSG_Q_ID idBalErreurs)
{
	PALETTE  palette;
	MESSAGE_LOG_ERR messageExit;
	MESSAGE_IHM messageExitIHM;
	
	for(;;)
	{
		if( msgQReceive(idBalPalettes, (char *) &palette, sizeof(PALETTE),WAIT_FOREVER) != ERROR)
		{
			if(palette.id == -1) //Arret de production
			{
				messageExit.type = LOG_EXIT;
				strcpy(messageExitIHM.message, "arret");
				msgQSend(idBalLogs, (char*) &messageExit, sizeof(MESSAGE_LOG_ERR), WAIT_FOREVER, MSG_PRI_NORMAL);
				msgQSend(idBalErreurs, (char*) &messageExit, sizeof(MESSAGE_LOG_ERR), WAIT_FOREVER, MSG_PRI_NORMAL);
				msgQSend(idBalIHM, (char*) &messageExitIHM, sizeof(MESSAGE_LOG_ERR), WAIT_FOREVER, MSG_PRI_NORMAL);
				return;
			}else{
				insererPalette(&palette, idBalLogs);
			}
		}
	}
	//strcpy(receptionPalette , "");
}

void insererPalette(PALETTE * p, MSG_Q_ID idBalLogs)
{
	int i = 0;
	PALETTE * palette = p;
	MESSAGE_LOG_ERR log;
	log.type = LOG_NORMAL;
	log.type_erreur = NULL;
	sprintf(log.message , "Palette d'id %d insérée dans l'entrepot\0", palette->id);
	if(p->type == PIECETYPE_A)//Insertion de palette selon le type
	{
		for( i =0; i < CAPACITE_PALETTE; i++)
		{
			if(paletteTypeA[i] == NULL)
			{
				paletteTypeA[i] = palette;
				break;
			}
		}
	}else{
		for( i =0; i < CAPACITE_PALETTE; i++)
		{
			if(paletteTypeB[i] == NULL)
			{
				paletteTypeB[i] = palette;
				break;
			}
		}
	}
	msgQSend(idBalLogs,(char *) &log,sizeof(MESSAGE_LOG_ERR),WAIT_FOREVER,MSG_PRI_NORMAL);
}
